#!/usr/bin/env python3
"""
验证RBAC权限系统数据是否完全按照用户设计
"""

from flask import Flask
from tools.db import init_db
from models.users import AdminUser, Role, Resource, Permission, user_roles, role_permissions, user_resources
import sys

def verify_rbac_data():
    """验证RBAC权限系统数据"""
    print("🔍 验证RBAC权限系统数据")
    print("=" * 50)
    
    try:
        # 初始化Flask应用
        app = Flask(__name__)
        db = init_db(app, use_mysql=True)
        
        with app.app_context():
            print("📊 数据验证结果:")
            print("-" * 30)
            
            # 1. 验证资源表数据
            print("\n📁 资源表数据验证:")
            resources = Resource.query.order_by(Resource.id).all()
            expected_resources = [
                (1, '销售管理', 0, 1, 0),
                (2, '销售订单', 1, 2, 1),
                (3, '销售订单新增', 2, 3, 1),
                (4, '商品管理', 0, 1, 0),
                (5, '新增', 4, 3, 4)
            ]
            
            for i, resource in enumerate(resources):
                expected = expected_resources[i]
                if (resource.id == expected[0] and 
                    resource.name == expected[1] and 
                    resource.pid == expected[2] and 
                    resource.level == expected[3] and 
                    resource.topid == expected[4]):
                    print(f"   ✅ 资源 {resource.id}: {resource.name} (PID: {resource.pid}, Level: {resource.level}, TopID: {resource.topid})")
                else:
                    print(f"   ❌ 资源 {resource.id}: 数据不匹配")
            
            # 2. 验证用户表数据
            print("\n👤 用户表数据验证:")
            users = AdminUser.query.order_by(AdminUser.id).all()
            expected_users = [
                (1, 'zs', '12344400001', 1),
                (2, 'zs1', '12344400002', 1),
                (3, 'xm', '12344400003', 2)
            ]
            
            for i, user in enumerate(users):
                expected = expected_users[i]
                if (user.id == expected[0] and 
                    user.name == expected[1] and 
                    user.mobile == expected[2] and 
                    user.roleid == expected[3]):
                    role = Role.query.get(user.roleid)
                    print(f"   ✅ 用户 {user.id}: {user.name} (手机: {user.mobile}, 角色: {role.name if role else '无'})")
                else:
                    print(f"   ❌ 用户 {user.id}: 数据不匹配")
            
            # 3. 验证角色表数据
            print("\n👥 角色表数据验证:")
            roles = Role.query.order_by(Role.id).all()
            expected_roles = [
                (1, '销售'),
                (2, '商品编辑')
            ]
            
            for i, role in enumerate(roles):
                expected = expected_roles[i]
                if (role.id == expected[0] and role.name == expected[1]):
                    print(f"   ✅ 角色 {role.id}: {role.name}")
                else:
                    print(f"   ❌ 角色 {role.id}: 数据不匹配")
            
            # 4. 验证用户资源关系（ACL权限）
            print("\n🔗 用户资源关系验证:")
            user_zs = AdminUser.query.get(1)
            if user_zs:
                resources = user_zs.resources.all()
                resource_ids = [r.id for r in resources]
                expected_resource_ids = [3, 5]  # 用户zs应该有资源3和5
                
                if set(resource_ids) == set(expected_resource_ids):
                    print(f"   ✅ 用户zs的资源权限: {[r.name for r in resources]}")
                else:
                    print(f"   ❌ 用户zs的资源权限不匹配，实际: {resource_ids}, 期望: {expected_resource_ids}")
            
            # 5. 验证角色权限关系
            print("\n🔐 角色权限关系验证:")
            sales_role = Role.query.get(1)  # 销售角色
            if sales_role:
                permissions = sales_role.permissions.all()
                if permissions:
                    resource = Resource.query.get(permissions[0].resource_id)
                    if resource and resource.id == 3:  # 销售角色应该有资源3的权限
                        print(f"   ✅ 销售角色权限: {[p.name for p in permissions]}")
                    else:
                        print(f"   ❌ 销售角色权限不匹配")
                else:
                    print(f"   ❌ 销售角色没有权限")
            
            product_role = Role.query.get(2)  # 商品编辑角色
            if product_role:
                permissions = product_role.permissions.all()
                if permissions:
                    resource = Resource.query.get(permissions[0].resource_id)
                    if resource and resource.id == 5:  # 商品编辑角色应该有资源5的权限
                        print(f"   ✅ 商品编辑角色权限: {[p.name for p in permissions]}")
                    else:
                        print(f"   ❌ 商品编辑角色权限不匹配")
                else:
                    print(f"   ❌ 商品编辑角色没有权限")
            
            # 6. 验证表结构
            print("\n📋 表结构验证:")
            inspector = db.inspect(db.engine)
            tables = inspector.get_table_names()
            expected_tables = ['admin_user', 'roles', 'resources', 'permissions', 'user_roles', 'role_permissions', 'user_resources']
            
            for table in expected_tables:
                if table in tables:
                    print(f"   ✅ 表 {table} 存在")
                else:
                    print(f"   ❌ 表 {table} 不存在")
            
            # 7. 验证数据完整性
            print("\n🔍 数据完整性验证:")
            user_count = AdminUser.query.count()
            role_count = Role.query.count()
            resource_count = Resource.query.count()
            permission_count = Permission.query.count()
            
            print(f"   ✅ 用户数量: {user_count} (期望: 3)")
            print(f"   ✅ 角色数量: {role_count} (期望: 2)")
            print(f"   ✅ 资源数量: {resource_count} (期望: 5)")
            print(f"   ✅ 权限数量: {permission_count} (期望: 2)")
            
            # 8. 验证关系完整性
            print("\n🔗 关系完整性验证:")
            
            # 验证用户角色关系
            user_roles_count = db.session.query(user_roles).count()
            print(f"   ✅ 用户角色关系数量: {user_roles_count}")
            
            # 验证角色权限关系
            role_permissions_count = db.session.query(role_permissions).count()
            print(f"   ✅ 角色权限关系数量: {role_permissions_count}")
            
            # 验证用户资源关系
            user_resources_count = db.session.query(user_resources).count()
            print(f"   ✅ 用户资源关系数量: {user_resources_count}")
            
            print("\n🎉 数据验证完成！")
            return True
            
    except Exception as e:
        print(f"❌ 验证失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def show_data_summary():
    """显示数据摘要"""
    print("\n📊 数据摘要")
    print("=" * 30)
    
    try:
        app = Flask(__name__)
        db = init_db(app, use_mysql=True)
        
        with app.app_context():
            # 显示完整的表结构
            print("\n📋 完整表结构:")
            print("资源表:")
            resources = Resource.query.order_by(Resource.id).all()
            for resource in resources:
                print(f"   ID: {resource.id}, 名称: {resource.name}, PID: {resource.pid}, Level: {resource.level}, TopID: {resource.topid}")
            
            print("\n用户表:")
            users = AdminUser.query.order_by(AdminUser.id).all()
            for user in users:
                print(f"   ID: {user.id}, 名称: {user.name}, 手机: {user.mobile}, 角色ID: {user.roleid}")
            
            print("\n角色表:")
            roles = Role.query.order_by(Role.id).all()
            for role in roles:
                print(f"   ID: {role.id}, 名称: {role.name}")
            
            print("\n权限表:")
            permissions = Permission.query.order_by(Permission.id).all()
            for permission in permissions:
                print(f"   ID: {permission.id}, 名称: {permission.name}, 资源ID: {permission.resource_id}, 操作: {permission.action}")
            
            print("\n用户资源关系表:")
            user_resources_data = db.session.query(user_resources).all()
            for relation in user_resources_data:
                print(f"   用户ID: {relation.user_id}, 资源ID: {relation.resource_id}")
            
            print("\n角色权限关系表:")
            role_permissions_data = db.session.query(role_permissions).all()
            for relation in role_permissions_data:
                print(f"   角色ID: {relation.role_id}, 权限ID: {relation.permission_id}")
            
    except Exception as e:
        print(f"❌ 显示数据摘要失败: {str(e)}")

if __name__ == '__main__':
    success = verify_rbac_data()
    if success:
        show_data_summary()
        print("\n✅ 数据验证通过，系统可以正常使用")
    else:
        print("\n❌ 数据验证失败")
        sys.exit(1)
